<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

use think\Request;
use think\Db;
use think\Log;

function getHttpHeader() {
    // 解决跨域通配符*与include报错
    $origin = Request::instance()->server('HTTP_ORIGIN');
    $header['Access-Control-Allow-Origin'] = $origin;
    $header['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS, DELETE';
    $header['Access-Control-Allow-Headers'] = 'x-requested-with,content-type';
    // 携带cookie验证
    $header['Access-Control-Allow-Credentials'] = 'true'; // 一定要是字符串

    return $header;
}

function apiResponse($status = 0, $msg = null, $data = []) {
    // data
    $data = [
        'status'=>$status,
        'msg'=>$msg,
        'data'=>$data,
    ];

    return json($data, 200, getHttpHeader());
}

function getSearchCondition($formData) {

    $map = array(); // 查询条件

    if ($formData) {
        $formData = json_decode($formData);
        if (!empty($formData->fixed)) {
            $map['fixed_no'] = ['like', '%' . $formData->fixed . '%'];
        }
        if (!empty($formData->names)) {
            $map['MODEL_NAME'] = ['like', '%' . $formData->names . '%'];
        }

        if (!empty($formData->type)) {
            $map['type'] = ['like', '%' . $formData->type . '%'];
        }
        if (!empty($formData->username)) {
            $map['user_name'] = ['like', '%' .$formData->username. '%'];
        }
        if (!empty($formData->history_user)) {
            $map['historyUser'] = ['like', '%' . $formData->history_user . '%'];
        }
        if (!empty($formData->location)) {
            $map['location'] = $formData->location;
        }

        // 是0不是null
        if (isset($formData->status) == true && IN_STORE == $formData->status) {
            $map['model_status'] = $formData->status;
        } elseif (null != $formData->status) {
            $map['model_status'] = $formData->status;
        }
        if (!empty($formData->broken)) {
            $map['broken'] = ($formData->broken == 'Y') ? 1 : 0;
        }
        if (!empty($formData->depart)) {
            $map['department'] = $formData->depart;
        }
        if (!empty($formData->section)) {
            $map['section_manager'] = $formData->section;
        }
        if (!empty($formData->cpu)) {
            $map['cpu'] = ['like', '%' . $formData->cpu . '%'];
        }
        if (!empty($formData->memory)) {
            $map['MEMORY'] = ['like', '%' . $formData->memory . '%'];
        }
        if (!empty($formData->hardware)) {
            $map['HDD'] = ['like', '%' . $formData->hardware . '%'];
        }
        // 新增字段
        // 序列号
        if (!empty($formData->serial_no)) {
            $map['SERIAL_NO'] = ['like', '%' . $formData->serial_no . '%'];
        }
        // 流水号
        if (!empty($formData->serial_number)) {
            $map['serial_number'] = ['like', '%' . $formData->serial_number . '%'];
        }
        // 是否免3c
        if (!empty($formData->three_c_flag)) {
            $map['three_c_flag'] = ($formData->three_c_flag == 'Y') ? 1 : 0;
        }
        // 发票号
        if (!empty($formData->invoice_no)) {
            $map['invoice_no'] = ['like', '%' . $formData->invoice_no . '%'];
        }
        // 备注
        if (!empty($formData->remark)) {
            $map['remark'] = ['like', '%' . $formData->remark . '%'];
        }
        // 所属细分
        if (!empty($formData->category)) {
            $map['category'] = $formData->category;
        }
//        所属类别
        if (!empty($formData->big_category)) {
            $map['big_category'] = $formData->big_category;
        }
//        供应商
        if (!empty($formData->supplier)) {
            $map['supplier'] =  ['like', '%' . $formData->supplier . '%'];
        }
//        可否外借
        if (!empty($formData->can_borrow)) {
            $map['can_borrow'] = $formData->can_borrow;
        }
//        关联工单
        if (!empty($formData->worker_order)) {
            $map['worker_order'] = ['like', '%' . $formData->worker_order . '%'];
        }
//        主板
        if (!empty($formData->motherboard)) {
            $map['motherboard'] = ['like', '%' . $formData->motherboard . '%'];
        }
//        屏幕
        if (!empty($formData->screen_size)) {
            $map['screen_size'] = ['like', '%' . $formData->screen_size . '%'];
        }
        if (!empty($formData->return_order)) {
            $map['return_order'] = ['like', '%' . $formData->return_order . '%'];
        }

    }
    return $map;

}

function getSearchConditionV2($formData) {
    $map = array(); // 查询条件

    if ($formData) {
        $formData = json_decode($formData);
        if (!empty($formData->fixed)) {
            $map['fixed_no'] = ['like', '%' . $formData->fixed . '%'];
        }
        if (!empty($formData->names)) {
            $map['MODEL_NAME'] = ['like', '%' . $formData->names . '%'];
        }
        if (!empty($formData->type)) {
            $map['type'] = ['like', '%' . $formData->type . '%'];
        }
        if (!empty($formData->username)) {
            $map['user_name'] = ['like', '%' .$formData->username. '%'];
        }
        if (!empty($formData->history_user)) {
            $map['historyUser'] = ['like', '%' . $formData->history_user . '%'];
        }
        if (!empty($formData->location)) {
            $map['location'] = $formData->location;
        }
        // 是0不是null
        if (isset($formData->status) == true && IN_STORE == $formData->status) {
            $map['model_status'] = $formData->status;
        } elseif (null != $formData->status) {
            $map['model_status'] = $formData->status;
        }
        if (!empty($formData->broken)) {
            $map['broken'] = ($formData->broken == 'Y') ? 1 : 0;
        }
        if (!empty($formData->depart)) {
            $map['department'] = $formData->depart;
        }
        if (!empty($formData->section)) {
            $map['section_manager'] = $formData->section;
        }
        if (!empty($formData->cpu)) {
            $map['cpu'] = ['like', '%' . $formData->cpu . '%'];
        }
        if (!empty($formData->memory)) {
            $map['MEMORY'] = ['like', '%' . $formData->memory . '%'];
        }
        if (!empty($formData->hardware)) {
            $map['HDD'] = ['like', '%' . $formData->hardware . '%'];
        }
        // 新增字段
        // 序列号
        if (!empty($formData->serial_no)) {
            $map['SERIAL_NO'] = ['like', '%' . $formData->serial_no . '%'];
        }
        // 流水号
        if (!empty($formData->serial_number)) {
            $map['serial_number'] = ['like', '%' . $formData->serial_number . '%'];
        }
        // 是否免3c
        if (!empty($formData->three_c_flag)) {
            $map['three_c_flag'] = ($formData->three_c_flag == 'Y') ? 1 : 0;
        }
        // 发票号
        if (!empty($formData->invoice_no)) {
            $map['invoice_no'] = ['like', '%' . $formData->invoice_no . '%'];
        }
        // 备注
        if (!empty($formData->remark)) {
            $map['remark'] = ['like', '%' . $formData->remark . '%'];
        }
        // 区分
        if (!empty($formData->category)) {
            $map['category'] = $formData->category;
        }
        // 颜色
        if (!empty($formData->color)) {
            $map['color'] = $formData->color;
        }
        // 报关含有0的情况
        if (isset($formData->clearance)) {
            $map['clearance'] = $formData->clearance;
        }
    }
    return $map;

}

function getFormArray($formData) {
    $data = array(); // 查询条件

    if ($formData) {
        $formData = json_decode($formData);

        foreach ($formData as $key => $value) {
            $data[$key] = $value;
        }
        $data['broken'] = $data['broken'] == 'Y' ? 1 : 0;
        $data['three_c_flag'] = $data['three_c_flag'] == 'Y' ? 1 : 0;
    }

    return $data;
}


function itemChange($list) {
    $departArray = getDepart();
    $sectionArray = getSections();
    foreach ($list as $key => $row) {
        $row = exportChange($row, $departArray, $sectionArray);
        $list[$key] = $row;
    }
    return $list;
}

function itemChangeV2($list, $flag) {
    foreach ($list as $key => $row) {
        $row = exportChangeV2($row, $flag);
        $list[$key] = $row;
    }
    return $list;
}

// 这里是为了导出只有一次循环才加的.
function exportChange($row, $departArray, $sectionArray) {
    $statusArray = json_decode(STATUS, true);

    $brokenArray = json_decode(BROKEN, true);
    $threeArray = json_decode(THREE_C, true);
    $rejectArray = json_decode(REJECT_FLAG, true);

    $row['model_status'] =  $statusArray[$row['model_status']];
    $row['department'] = $departArray[$row['department']];
    $row['section_manager'] = $sectionArray[$row['section_manager']];
    $row['broken'] = $brokenArray[$row['broken']];
    $row['three_c_flag'] = $threeArray[$row['three_c_flag']];
    $row['reject_flag'] = $rejectArray[$row['reject_flag']];

    return $row;
}

function exportChangeV2($row, $flag) {
    $statusArray = json_decode(STATUS_V2, true);
    $brokenArray = json_decode(BROKEN, true);
    $threeArray = json_decode(THREE_C, true);
    $rejectArray = json_decode(REJECT_FLAG, true);
    $clearanceArray = json_decode(CLEARANCE, true);

    $row['model_status'] =  $statusArray[$row['model_status']];
    $row['broken'] = $brokenArray[$row['broken']];
    $row['three_c_flag'] = $threeArray[$row['three_c_flag']];
    $row['clearance'] = $clearanceArray[$row['clearance']];

    if (!$flag) {
        unset($row['actual_price']);
    }
    return $row;
}

function getColumns($type) {
    // 头部
    $column =[];

    try {
        $columns = Db::table('information_schema.columns')
            ->field('column_name as field, column_comment as comment')
            ->where('table_name', 'ems_main_engine')
            ->where('table_schema', config('database.database'))
            ->order('ordinal_position')->select();

        foreach ($columns as $value) {
            $column[] = $value[$type];
        }
        return $column;
    } catch (Exception $e) {
        Log::record('[Machine][getColumns] error' . $e->getMessage());
    }
    return $column;
}

function getColumnsV2($type, $flag) {
    // 头部
    $column =[];

    try {
        $columns = Db::table('information_schema.columns')
            ->field('column_name as field, column_comment as comment')
            ->where('table_name', 'sms_main_engine')
            ->where('table_schema', config('database.database'))
            ->order('ordinal_position')->select();

        foreach ($columns as $value) {
            if ($value[$type] == '内部价格') {
                if ($flag) {
                    $column[] = $value[$type];
                }
            } else {
                $column[] = $value[$type];
            }
        }
        return $column;
    } catch (Exception $e) {
        Log::record('[Machine][getColumnsV2] error' . $e->getMessage());
    }

    return $column;
}

function getColumnsByTableName($type, $tableName) {
    // 头部
    $column =[];

    try {
        $columns = Db::table('information_schema.columns')
            ->field('column_name as field, column_comment as comment')
            ->where('table_name', $tableName)
            ->where('table_schema', config('database.database'))
            ->order('ordinal_position')->select();

        foreach ($columns as $value) {
            $column[] = $value[$type];
        }
        return $column;
    } catch (Exception $e) {
        Log::record('[Machine][getColumnsByTableName] error' . $e->getMessage());
    }
    return $column;
}

/**
 * @param $res
 * @param $userId
 * @param $mainPage
 * 自定义内容的修改
 */
function itemCustomChange($res, $userId, $mainPage) {

    $departArray = getDepart();
    $sectionArray = getSections();

    foreach ($res as $key => $item) {
        if ($mainPage) {
            if (empty($userId)) {
                $item['hasApply'] = true;
            } else {
                // 判断是否要有取消申请
                if (BORROW_REVIEW == $item['model_status'] && $userId == $item['user_id'] ) {
                    $item['hasApply'] = true;
                } else {
                    $item['hasApply'] = false;
                }
            }
        }

        try {
            // 判断借用人所属课
            if (!empty($item['user_id'])) {
                // 根据user_id查找
                $rA = Db::table('ems_user')->where('IS_DELETED', 0)
                    ->where('USER_ID', $item['user_id'])->find();

                $rB = Db::table('users')->where('ems_uid', $rA['ID'])
                    ->where('active', 1)->find();
                if (!empty($rB)) {
                    $item['user_depart_info'] = $rB['department'] . '-' . $rB['section'];
                } else {
                    $item['user_depart_info'] = 'N/A';
                }
            } else {
                $item['user_depart_info'] = null;
            }
        } catch (Exception $e) {
            Log::record('[Machine][itemCustomChange] error ' . $e->getMessage());
            return apiResponse(ERROR, 'server error');
        }

        $res[$key] = exportChange($item, $departArray, $sectionArray);
    }

    return $res;
}

function getMyType($type) {
    // 设置是否发送邮件
    $sendMailOption = true;

    if (!$sendMailOption) {
        return 'Test';
    }
    return $type;
}

function getDepart() {
    try {
        $res = Db::table('trc_group')->distinct(true)->field('department_id, depart_desc')
            ->where('is_sale', 0)->select();
        $depart = [];
        foreach ($res as $item) {
            $depart[$item['department_id']] = $item['depart_desc'];

        }
        return $depart;
    } catch (Exception $e) {
        Log::record('[common][getDepart] error' . $e->getMessage());
        return apiResponse(ERROR, ' server error');
    }

}

function getSections() {
    try {
        $res = Db::table('trc_group')->distinct(true)->field('section_id, section_desc')
            ->where('is_sale', 0)->select();
        $section = [];
        foreach ($res as $item) {
    	 	if ($item['section_desc'] != 'EOL') {
        		$section[$item['section_id']] = $item['section_desc'];
        	}
           //  $section[$item['section_id']] = $item['section_desc'];

        }
        return $section;
    } catch (Exception $e) {
        Log::record('[common][getSections] error' . $e->getMessage());
        return apiResponse(ERROR, ' server error');
    }

}
